package com.bw.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bw.domain.Onlineusers;
import com.bw.domain.SysUser;
import com.bw.service.OnlineUserService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("object_online")
public class ObjectOnlineuUserService implements OnlineUserService {
    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    HttpServletRequest request;

    @Override
    public boolean addOnlineUser(String token, SysUser user) {
        Onlineusers onlineusers = new Onlineusers();
        /*
         * 根据request获取浏览器信息,本机IP，操作系统等。
         * */

        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //获取client主机ip
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //生成一个随机编号
        onlineusers.setNumber(UUID.randomUUID().toString());
        //登录名称
        onlineusers.setNickname(user.getUserName());
        //onlineusers.setDepartment();//部门
        //本机IP
        onlineusers.setIp(ip);
        String address="";
        String resJson = HttpUtil.get("http://ip-api.com/json/"+ip+"?lang=zh-CN&fields=585727");
        JSONObject obj = JSONUtil.parseObj(resJson);
        Boolean status = obj.getBool("status");
        if(status){
            String country = obj.getStr("country");
            String regionName = obj.getStr("regionName");
            String city = obj.getStr("city");
            String district = obj.getStr("district");
            address=obj.getStr(country+"-"+regionName+"-"+city+"-"+district);
        }else {
            address="内网IP";
        }
        onlineusers.setLoginLocation(address);//登录地点
        //浏览器
        onlineusers.setBrowserj(userAgent.getBrowser().getName());
        //操作系统
        onlineusers.setSystem(userAgent.getOperatingSystem().getName());
        //登录时间
        onlineusers.setLoginTime(new Date());

        System.out.println(onlineusers + "/////////////////////////////////////////////////////");


        /*
         * 加入到redis中,加个前缀
         * */
        redisTemplate.opsForValue().set("online_user." + token, onlineusers, 30, TimeUnit.MINUTES);


        return true;
    }

    @Override
    public List<Onlineusers> lists(int page, int size,Onlineusers onlineusers) {

        /*
         * 从redis中获取所有的以“online_user.*”为前缀的key。
         * */
        Set keys = redisTemplate.keys("online_user.*");

        List<String> query = (List<String>) keys.stream()
                .sorted()
                .skip((page - 1) * size)
                .limit(size)
                .collect(Collectors.toList());
        List<Onlineusers> list = (List<Onlineusers>) redisTemplate.opsForValue().multiGet(query);
        if(ObjectUtil.isNotEmpty(onlineusers.getLoginLocation())){
            List<Onlineusers> queryList=new ArrayList<>();
            list.stream().forEach(onlineuser -> {
                if (onlineuser.getLoginLocation().contains(onlineusers.getLoginLocation())){
                    queryList.add(onlineuser);
                }
            });
            if (ObjectUtil.isNotEmpty(onlineusers.getNickname())){
                queryList.stream().forEach(onlineuser -> {
                    if (!onlineuser.getNickname().contains(onlineusers.getNickname())){
                        queryList.remove(onlineuser);
                    }
                });
            }
            return queryList;
        }
        if(ObjectUtil.isNotEmpty(onlineusers.getNickname())){
            List<Onlineusers> queryList=new ArrayList<>();
            list.stream().forEach(onlineuser -> {
                if (onlineuser.getNickname().contains(onlineusers.getNickname())){
                    queryList.add(onlineuser);
                }
            });
            return queryList;
        }
        return list;
    }


}
